package com.toune.movie.base;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.toune.movie.R;
import com.toune.movie.mvp.activity.LoginActivity;
import com.toune.movie.mvp.activity.MainActivity;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zhy.autolayout.AutoLayoutActivity;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by wangjitao on 2016/11/8 0008.
 * 基类Activity的封装
 * 一般使用mvp模式的话会在BaseActivity中进行P和V的初始化绑定
 */
public abstract class BaseActivity<T extends BasePresenterImpl> extends AutoLayoutActivity implements BaseView {
    protected T mPresenter;
    private Unbinder mUnbinder;
    public BaseActivity context;

    /**
     * 传来的initViewID对应的View
     */
    public View viewActivity = null;
    //title相关  标题
    public String titleStr = "";
    //下拉刷新
    private RefreshLayout refreshLayout;
    public Toolbar toolbar;
    private RelativeLayout multipleStatusView;
    private TextView titleTv;

    public enum TransitionMode {
        LEFT, RIGHT, TOP, BOTTOM, SCALE, FADE
    }

//    private ImmersionBar mImmersionBar;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        View view = View.inflate(context, R.layout.activity_basic, null);
        setContentView(view);
        AutoUtils.auto(view);
        multipleStatusView = findViewById(R.id.multiple_status_view);
        titleTv = findViewById(R.id.title_tv);
        toolbar = findViewById(R.id.toolbar);
        int initViewID = getLayout();
        this.viewActivity = View.inflate(context, initViewID, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        multipleStatusView.addView(viewActivity, layoutParams);
        RxActivityTool.addActivity(this);
        mUnbinder = ButterKnife.bind(this);
        //initPresenter()是抽象方法，让view初始化自己的presenter
        mPresenter = initPresenter();
        //presenter和view的绑定
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }
        //initActtivity是抽象方法，让view完成自身各种控件的初始化
        //butter绑定
        init(savedInstanceState);
        //返回的不是null和空则是为有标题，标题的为返回值
        titleStr = getTitleStr();
        //标题  ：布局文件中引入lyout_title
        //标题  ：布局文件中引入lyout_title
        if (!TextUtils.isEmpty(titleStr)) {
//            TextView textView = viewActivity.findViewById(R.id.titleTv);
//            textView.setText(titleStr);
//            LinearLayout backIv = viewActivity.findViewById(R.id.backLl);
//            backIv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onBackIv();
//                }
//            });
            setToolBar(toolbar, titleStr);
        } else {
            toolbar.setVisibility(View.GONE);
        }
        //引入下拉刷新，加载更多
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    refreData();
                    refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                }
            });
            refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(RefreshLayout refreshlayout) {
                    loadMore();
                    refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                }
            });
        }
        //权限
        AndPermission.with(this)
                .permission(Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE,
//                        Permission.CAMERA,
                        Manifest.permission.SYSTEM_ALERT_WINDOW,
//                        Permission.RECORD_AUDIO,
                        Manifest.permission.BLUETOOTH)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        // TODO what to do.
                    }
                }).onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                // TODO what to do
            }
        }).start();
//        MonitorService.startThis(context);
        initEventAndData();
    }

    @Override
    protected void onResume() {
        if (mPresenter != null) {
            mPresenter.onResume();
        }
        super.onResume();
    }

    // 实例化presenter
    public abstract T initPresenter();

    @Override
    protected void onStart() {
        super.onStart();

    }


    public abstract void loadMore();

    public abstract void refreData();

    /**
     * 返回按钮，可不实现
     */
    public void onBackIv() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
//        if (mImmersionBar != null)
//            mImmersionBar.destroy();
        //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
    }

    protected void setToolBar(Toolbar toolbar, String title) {
        if (toolbar == null) {
            return;
        }
        toolbar.setTitle("");
        titleTv.setText(title);
        toolbar.setNavigationIcon(R.mipmap.arrow_left);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackIv();
            }
        });
    }

    public void setTitleStr(String name) {
        titleTv.setText(name);
    }

    public abstract void init(Bundle savedInstanceState);

    protected abstract int getLayout();

    protected abstract String getTitleStr();

    protected abstract void initEventAndData();


    private long exitTime = 0;

    /**
     * 判断是否是主页面
     *
     * @return
     */
    private boolean isLoginOut() {
        return getClass().getSimpleName().equals(
                MainActivity.class.getSimpleName())
                | getClass().getSimpleName().equals(LoginActivity.class.getSimpleName());
    }

    @Override
    public void onBackPressed() {
        if (isLoginOut()) {
            //连续按2次返回键退出
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                RxToast.showToast("再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                App.getInstance().exitApp();
            }
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 这还有一系列的第三方SDK的初始化
     */
}